import request from "@/utils/request";
import { downloadFileByData } from "@/utils/download";

/**
 * Brokerrecord 实体类型定义
 * 
 * @author guagua
 * @date 2025-06-12 13:51:39
 */
export interface CustomerRecordModel {
  /** 主键ID */

  /** 类型 */
  type?: string;

  /** 描述 */
  description?: string;

  /** 详情 */
  details?: string;

  /** 附件 */
  attachments?: string;

  /** 联系方式 */
  communicationType?: string;

  /** 联系时长 */
  duration?: number;

  /** broker */
  customerId: string;

  /** 提醒时间 */
  reminderTime?: string | Date;

  /** 提醒人 */
  assignedTo?: string;

  /** 联系时间 */
  communicationTime?: string | Date;

  /** 唯一主键 */
  id?: string;

  /** 父级主键集合 */
  orgIds?: string;

  /** 修改人 */
  updateBy?: string;

  /** 创建时间 */
  createTime?: string;

  /** 创建者 */
  createBy?: string;

  /** 修改时间 */
  updateTime?: string;

  /** 乐观锁 */
  version?: number;


}

/**
 * 分页查询参数类型
 */
export interface CustomerRecordQueryParams {
  /** 页码 */
  pageNo?: number;

  /** 每页条数 */
  pageSize?: number;

  /** 客户ID */
  customerId_EQ?: string;

  /** 类型 */
  type_EQ?: string;
  /** 描述 */
  description_LIKE?: string;
  /** 详情 */
  details_LIKE?: string;
  /** 附件 */
  attachments_EQ?: string;
  /** 联系方式 */
  communicationType_EQ?: string;
  /** 联系时长 */
  duration_EQ?: number;
  /** broker */
  brokerId_EQ?: string;
  /** 提醒时间开始 */
  reminderTime_BEGIN?: string;
  /** 提醒时间结束 */
  reminderTime_END?: string;
  /** 提醒人 */
  assignedTo_EQ?: string;
  /** 联系时间开始 */
  communicationTime_BEGIN?: string;
  /** 联系时间结束 */
  communicationTime_END?: string;
  /** 创建时间开始 */
  createTime_BEGIN?: string;
  /** 创建时间结束 */
  createTime_END?: string;
  /** 创建者 */
  createBy_EQ?: string;

  /** 排序字段 */
  orderBy?: string;

  /** 排序方式 */
  sortOrder_ORDER?: 'ASC' | 'DESC';
}

/**
 * API 响应类型
 */
export interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
  timestamp: number;
}

/**
 * 分页响应数据类型
 */
export interface PageResult<T> {
  rows: T[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

/**
 * 获取Brokerrecord分页列表
 * @param params 查询参数
 * @returns Promise<ApiResponse<PageResult<BrokerRecordModel>>>
 */
export function getList(params: CustomerRecordQueryParams): Promise<ApiResponse<PageResult<CustomerRecordModel>>> {
  return request({
    url: "/api/v1/customer/Record/findPage",
    method: "get",
    params,
  });
}

/**
 * 新增Brokerrecord
 * @param data 新增数据
 * @returns Promise<ApiResponse<BrokerRecordModel>>
 */
export function doInsert(data: Partial<CustomerRecordModel>): Promise<ApiResponse<CustomerRecordModel>> {
  return request({
    url: "/api/v1/customer/Record/insert",
    method: "post",
    data,
  });
}

/**
 * 更新Brokerrecord
 * @param data 更新数据
 * @returns Promise<ApiResponse<BrokerRecordModel>>
 */
export function doUpdate(data: CustomerRecordModel): Promise<ApiResponse<CustomerRecordModel>> {
  return request({
    url: "/api/v1/customer/Record/update",
    method: "post",
    data,
  });
}

/**
 * 删除Brokerrecord
 * @param params 删除参数
 * @returns Promise<ApiResponse<boolean>>
 */
export function doDelete(params: { id: string }): Promise<ApiResponse<boolean>> {
  return request({
    url: "/api/v1/customer/Record/del",
    method: "post",
    params,
  });
}

/**
 * 批量删除Brokerrecord
 * @param params 批量删除参数
 * @returns Promise<ApiResponse<boolean>>
 */
export function doDeleteAll(params: { ids: string }): Promise<ApiResponse<boolean>> {
  return request({
    url: "/api/v1/customer/Record/delAll",
    method: "post",
    params,
  });
}

/**
 * 导出Excel 目前只支持一层参数传递
 * @param params 导出参数
 * @returns Promise<void>
 */
export async function doExportExcel(params: CustomerRecordQueryParams): Promise<void> {
  const authURL = "/api/v1/customer/Record/excel/auth/export";

  const downloadURL = "/api/v1/customer/Record/excel/export/";

  try {
    // 认证
    const response: ApiResponse<string> = await request({
      url: authURL,
      method: "get",
      params,
    });

    if (response.data) {
      // 下载文件
      downloadFileByData(downloadURL + response.data, params);
    }
  } catch (error) {
    console.error('导出Excel失败:', error);
    throw error;
  }
}

/**
 * 下载导入模版
 * @returns Promise<void>
 */
export async function doDownloadTemplate(): Promise<void> {
  const authURL = "/api/v1/customer/Record/excel/auth/import-template-export";

  const downloadURL = "/api/v1/customer/Record/excel/export/";

  try {
    // 认证
    const response: ApiResponse<string> = await request({
      url: authURL,
      method: "get",
    });

    if (response.data) {
      // 下载文件
      downloadFileByData(downloadURL + response.data, {});
    }
  } catch (error) {
    console.error('下载模板失败:', error);
    throw error;
  }
}

/**
 * 导入Excel
 * @param data 上传的文件数据
 * @returns Promise<ApiResponse<any>>
 */
export function doImportExcel(data: FormData): Promise<ApiResponse<any>> {
  return request({
    url: "/api/v1/customer/Record/importExcel",
    method: "post",
    // 最长超时时间 3 分钟
    timeout: 180000,
    headers: {
      "Content-Type": "multipart/form-data"
    },
    data,
  });
}

/**
 * 获取Brokerrecord详情
 * @param id 主键ID
 * @returns Promise<ApiResponse<BrokerRecordModel>>
 */
export function getById(id: string): Promise<ApiResponse<CustomerRecordModel>> {
  return request({
    url: `/api/v1/customer/Record/findById/${id}`,
    method: "get",
  });
}

/**
 * 启用/禁用Brokerrecord
 * @param params 启用禁用参数
 * @returns Promise<ApiResponse<boolean>>
 */
export function doEnable(params: { id: string; enable: boolean }): Promise<ApiResponse<boolean>> {
  return request({
    url: "/api/v1/customer/Record/enable",
    method: "post",
    params,
  });
}

// ========================================
// 客户操作记录相关API
// ========================================

/**
 * 新增客户时创建记录
 * @param customerId 客户ID
 * @param customerData 客户数据
 * @returns Promise<ApiResponse<any>>
 */
export function createCustomerAddRecord(customerId: string, customerData: any): Promise<ApiResponse<any>> {
  return request({
    url: "/api/v1/customer/Record/createCustomerAddRecord",
    method: "post",
    params: { customerId },
    data: customerData,
  });
}

/**
 * 修改客户时创建记录（比较新旧数据）
 * @param customerId 客户ID
 * @param oldData 修改前数据
 * @param newData 修改后数据
 * @returns Promise<ApiResponse<any>>
 */
export function createCustomerUpdateRecord(customerId: string, oldData: any, newData: any): Promise<ApiResponse<any>> {
  return request({
    url: "/api/v1/customer/Record/createCustomerUpdateRecord",
    method: "post",
    params: {
      customerId,
      oldData: JSON.stringify(oldData),
      newData: JSON.stringify(newData)
    },
  });
}

/**
 * 修改客户状态时创建记录
 * @param customerId 客户ID
 * @param oldStatus 原状态
 * @param newStatus 新状态
 * @param reason 修改原因（可选）
 * @returns Promise<ApiResponse<any>>
 */
export function createCustomerStatusChangeRecord(
  customerId: string,
  oldStatus: string,
  newStatus: string,
  reason?: string
): Promise<ApiResponse<any>> {
  const params: any = {
    customerId,
    oldStatus,
    newStatus
  };

  if (reason) {
    params.reason = reason;
  }

  return request({
    url: "/api/v1/customer/Record/createCustomerStatusChangeRecord",
    method: "post",
    params,
  });
}